/**
 * @author Timzhong <2164992949@qq.com>
 * 柱状图，用于渲染key-value类型数据。
 */
import { Component, Input, OnInit, OnChanges } from '@angular/core';
import { ChartData, ChartTheme } from '../chart-option';

@Component({
  selector: 'app-bar-chart',
  templateUrl: './bar-chart.component.html',
  styleUrls: ['./bar-chart.component.scss']
})
export class BarChartComponent implements OnChanges {
  @Input() chartData: ChartData[] = [{ name: 'test', value: 10 }];
  @Input() chartTheme: ChartTheme = {};
  @Input() rowDirection = false;
  @Input() givenHeight = '400px';
  @Input() givenXAxis = '';
  @Input() givenYAxis = '';
  getHeight() {
    return this.givenHeight;
  }

  constructor() {}
  options = {};

  ngOnChanges(): void {
    const names: string[] = [];
    const values: number[] = [];
    let xAxisType = 'category';
    let yAxisType = 'value';
    this.chartData.forEach((pair) => {
      names.push(pair.name);
      values.push(pair.value);
    });
    if (this.rowDirection) {
      [xAxisType, yAxisType] = [yAxisType, xAxisType];
    }
    this.options = {
      title: {
        text: this.chartTheme.title || null,
        show: this.chartTheme.title ? true : false
      },
      color: [this.chartTheme.color || '#3398DB'],
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: [
        {
          name: this.givenXAxis,
          nameLocation: 'end',
          type: xAxisType,
          data: !this.rowDirection ? names : null,
          axisTick: {
            alignWithLabel: true
          }
        }
      ],
      yAxis: [
        {
          name: this.givenYAxis,
          nameLocation: 'end',
          type: yAxisType,
          data: this.rowDirection ? names : null
        }
      ],
      series: [
        {
          name: 'Counters',
          type: 'bar',
          barWidth: '60%',
          data: values
        }
      ]
    };
  }
}
